//
//  SYMomentsFirstTableViewController.m
//  BShouGongKe
//
//  Created by lanou on 15/8/11.
//  Copyright (c) 2015年 L750. All rights reserved.
//

#import "SYMomentsFirstTableViewController.h"
#import "Header.h"
#import "SYMomentsTableViewCell.h"
#import "MYRequestManger.h"
#import "SYHeaderView.h"
#import "SYDetailViewController.h"
#import "LORefresh.h"
#import "FMDatabase.h"
#import "SYFileHandle.h"
#import "SYLoginViewController.h"
#import "SYFileHandle.h"


typedef NS_ENUM(NSInteger, RefreshType){
    RefreshTypeNew,
    RefreshTypeMore
};


@interface SYMomentsFirstTableViewController ()<headerDegelate>
@property (nonatomic,strong)SYMomentsTableViewCell *momentsCell;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)SYHeaderView *topView;
@property (nonatomic,assign)NSInteger page;
@property (nonatomic,assign)RefreshType refreshType;
@property (nonatomic,strong)FMDatabase *db;
@end

@implementation SYMomentsFirstTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArr = [NSMutableArray arrayWithCapacity:0];
    [self navigationItemTitleColor];
    UIButton*leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,30*0.6,30*0.6)];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"]forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(searchprogram) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*leftItem = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem= leftItem;
    
    [self.tableView registerClass:[SYMomentsTableViewCell class] forCellReuseIdentifier:@"cell"];
    _page = 1;
    _topView = [[SYHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    [self parserData];
    self.tableView.backgroundColor = [UIColor colorWithRed:247 / 255.0 green:239 / 255.0 blue:239 / 255.0 alpha:1];
    //刷新与加载
    __weak SYMomentsFirstTableViewController *fstVC = self;
    __weak NSMutableArray *array = _dataArr;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        _page = 1;
        _refreshType = RefreshTypeNew;
        [array removeAllObjects];
        [fstVC parserData];
    }];
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _page = _page + 1;
        _refreshType = RefreshTypeMore;
        [fstVC parserData];
    }];
    //创建数据库
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [str stringByAppendingPathComponent:@"like.db"];
    _db = [FMDatabase databaseWithPath:filePath];
    if (![_db open]) {
        NSLog(@"%@",filePath);
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [_db executeUpdate:@"create table quanzi (title text,imgstr text,backupStr text,name text,count int,fans text,username text )"];
    });

}

- (void)searchprogram{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)navigationItemTitleColor
{
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:_naviTitle];
    customLab.textAlignment = NSTextAlignmentCenter;
    customLab.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = customLab;
}


- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}


   //*************数据解析*************//

- (void)parserData{
    if (_backupStr.length == 0) {
        _backupStr = _urlModel.baseArr[_arrIndex][_urlIndex];
    }
    NSRange range = [_backupStr rangeOfString:@"&page"];
    NSMutableString *urlStr = [_backupStr mutableCopy];
    [urlStr replaceCharactersInRange:NSMakeRange(range.location + 6, 1) withString:[NSString stringWithFormat:@"%ld",_page]];
    [MYRequestManger manager:POST RequestWith:urlStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *arr = dict[@"data"];
        if (arr.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"无更多数据" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [self.tableView.defaultFooter endRefreshing];
            [alert show];
            [alert dismissWithClickedButtonIndex:0 animated:YES];
            return;
        }
        for (NSDictionary *dic in arr) {
            SYMomentsFirstModel *model = [[SYMomentsFirstModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArr addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.defaultHeader endRefreshing];
        [self.tableView.defaultFooter endRefreshing];
    } error:^(NSError *error) {
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    _momentsCell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    _momentsCell.model = _dataArr[indexPath.row];
    return _momentsCell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [SYMomentsTableViewCell heightForCellWithModel:_dataArr[indexPath.row]];
}


   //*************自定义区头*************//

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    _topView.model = _typeModel;
    NSString *userName = [[SYFileHandle shareInstance] phoneNumber];
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    FMResultSet *result = [_db executeQuery:@"select title,imgstr,backupStr from quanzi where username = ?",userName];
    while ([result next]) {
        NSString *title = [result stringForColumn:@"title"];
        [arr addObject:title];
    }
    for (NSString *str in arr) {
        if ([str isEqualToString:_typeModel.quan_slogan]) {
            [_topView.addButton setBackgroundImage:[UIImage imageNamed:@"quan_detail_quit@3x"] forState:UIControlStateNormal];
        }
    }
    [result close];
    
    _topView.delegate = self;
    _topView.backgroundColor = [UIColor whiteColor];
    return _topView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 80;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SYDetailViewController *detailVC = [[SYDetailViewController alloc]init];
    SYMomentsFirstModel *model = _dataArr[indexPath.row];
    
    NSMutableString *temp = [model.share_url mutableCopy];
    [temp insertString:@"shougong." atIndex:24];
    [temp deleteCharactersInRange:NSMakeRange(0, 17)];
    NSString *str = [NSString stringWithFormat:@"%@",temp];
    
    detailVC.urlStr = str;
    //detailVC.dataArr = _dataArr;
    detailVC.backupTitle = model.text;
    detailVC.backupImg = model.face_img;
    detailVC.jumpIndex = _jumpIndex;
    _jumpIndex = 0;
    [self.navigationController pushViewController:detailVC animated:YES];
}


   //*************添加圈子*************//

- (void)collectionQuanzi{
    BOOL islogin = [[SYFileHandle shareInstance] loginState];
    if (!islogin) {
        SYLoginViewController *loginVC = [[SYLoginViewController alloc]init];
        __weak SYLoginViewController *tempVC = loginVC;
        loginVC.loginAppear = ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [tempVC.longinView endEditing:YES];
            });
            dispatch_async(dispatch_get_main_queue(), ^{
                [tempVC dismissViewControllerAnimated:YES completion:nil];
            });
        };
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    NSString *userName = [[SYFileHandle shareInstance] phoneNumber];
    FMResultSet *result = [_db executeQuery:@"select title,imgstr,backupStr from quanzi where username = ?",userName];
    while ([result next]) {
        NSString *title = [result stringForColumn:@"title"];
        [arr addObject:title];
    }
    //第一次添加
    if (arr.count == 0) {
        NSArray *array = _typeModel.quan_fans;
        for (int i = 0; i < array.count; i++) {
            NSString *str = [NSString stringWithFormat:@"insert into quanzi (title ,imgstr ,backupStr ,name ,count ,fans ,username) values ('%@','%@','%@','%@','%d','%@','%@')",_typeModel.quan_slogan,_typeModel.quan_logo,self.backupStr,_typeModel.quan_name,(int)_typeModel.new_say_count,array[i],userName];
            [_db executeUpdate:str];
            
        }
        [_topView.addButton setBackgroundImage:[UIImage imageNamed:@"quan_detail_quit@3x"] forState:UIControlStateNormal];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你已成功加入该圈" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }
    //当数据库里存在多个时
    //判断如果已收藏
    for (NSString *title in arr) {
        if ([title isEqualToString:_typeModel.quan_slogan]) {
            [_db executeUpdate:@"delete from quanzi where title = ? and username = ?",_topView.textLabel.text,userName];
            [_topView.addButton setBackgroundImage:[UIImage imageNamed:@"quan_detail_add@3x"] forState:UIControlStateNormal];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你已成功退出该圈" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alert show];
            [alert dismissWithClickedButtonIndex:0 animated:YES];
            return;
        }
    }
    //如果还没有收藏
    NSArray *array = _typeModel.quan_fans;
    for (int i = 0; i < array.count; i++) {
        NSString *str = [NSString stringWithFormat:@"insert into quanzi (title ,imgstr ,backupStr ,name ,count,fans,username) values ('%@','%@','%@','%@','%d','%@','%@')",_typeModel.quan_slogan,_typeModel.quan_logo,self.backupStr,_typeModel.quan_name,(int)_typeModel.new_say_count,array[i],userName];
        [_db executeUpdate:str];
        
    }
    [_topView.addButton setBackgroundImage:[UIImage imageNamed:@"quan_detail_quit@3x"] forState:UIControlStateNormal];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你已成功加入该圈" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    [result close];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
